#!/usr/bin/env ./script/runner
# author: matias

# == Synopsis
#
# bulk_add.rb: Adds email addresses to the database.
# Expects one email address per line.
#
# == Usage
#
# bulk_add.rb [OPTION]
#
# -h, --help:
#    show help
#
# -s, --status 'active'|'inactive':
#    add the emails as active / inactive.
#    If the contact already exists, the status will not be updated,
#    unless -force flag is used.
#    
# -f, --force:
#    force the update of the contact's status, even if the contact already
#    exists.

require 'getoptlong'
require 'rdoc/usage'

if ARGV.length == 0
  puts "Missing argument (try --help)"
  exit 0
end

opts = GetoptLong.new(
  [ '--help', '-h', GetoptLong::NO_ARGUMENT],
  [ '--status', '-s', GetoptLong::REQUIRED_ARGUMENT],
  [ '--force', '-f', GetoptLong::OPTIONAL_ARGUMENT]
)

status = true
force = false

opts.each do |opt, arg|
  case opt
  when '--help'
    RDoc::usage
  when '--status'
    if arg != "active" and arg != "inactive"
      puts "Invalid argument: expected 'active' or 'inactive'"
      exit
    end
    status = arg == 'active'
  when '--force'
    force = true
  end
end

total_count = new_count = update_count = untouched_count = errors = 0
$stdin.each do |email|
  total_count += 1
  
  email.chop!  # remove newline
  
  contact = Contact.find_by_email(email)
  new_record = contact.nil?
  
  if new_record
    contact = Contact.new(:email => email)
  end
  
  if new_record or force
    contact.active = status

    if !contact.save(perform_validation=true)
      print "line #{total_count} (#{email}): #{contact.errors.full_messages.to_sentence}\n"
      errors += 1
    else
      if new_record
        new_count += 1
      else
        update_count += 1
      end
    end
  else
    untouched_count += 1
  end
end

puts "#{total_count} emails processed"
puts "\t#{new_count} added"
puts "\t#{update_count} updated"
puts "\t#{untouched_count} untouched"
puts "\t#{errors} errors"
